﻿using System;
using System.Runtime.Serialization.Json;
using System.Web.Mvc;

namespace Isaac.Joy.WebHelper
{
    public class JsonModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext modelBindingContext)
        {
            if (controllerContext == null)
            {
                throw new ArgumentException("controllerContext");
            }
            if (modelBindingContext == null)
            {
                throw new ArgumentException("modelBindingContext");
            }

            controllerContext.HttpContext.Request.InputStream.Position = 0; 
            var serialize = new DataContractJsonSerializer(modelBindingContext.ModelType);
            return serialize.ReadObject(controllerContext.HttpContext.Request.InputStream);
        }
    }
}
